<?php
/**
 * Created by PhpStorm.
 * User: bzyy
 * Date: 2015-7-22 19:27:01
 */

class PostexpruleModel extends BaseModel{

    public $table = 'post_exp_rule';

    public $prikey = 'id';

    public $_autov = array(

        'express_id' => array(
            'required'  => true,
            'filter'    => 'trim',
            'reg'   => '/\d+/'
        ),
        'postal_id' => array(
            'required'  => true,
            'filter'    => 'trim',
            'reg'   => '/\d+/'
        ),
        'code' => array(
            'required'  => true,
            'filter'    => 'trim',
            'reg'   => '/\d+/'
        ),
    );


    /**
     * 添加收费规则
     * @auth bzyy
     * 2015-7-23 13:36:48
     */
    public function add($data)
    {
        //检测重复记录的相关数据
        //添加
        $regions = $data['regions'];
        unset($data['regions']);
        $f = parent::add($data);

        //添加地区等多个设置内容的绑定

        $model = m('postruleregion');


        return $f;
    }


    /**
     * 编辑规则
     * @auth bzyy
     * 2015-7-23 15:43:55
     */
    public function editRules($rules,$express_id)
    {
        //看所有的地区是否有重复的现象
        $area_ids = array();
        //$rule_ids = array();
        foreach($rules as $val)
        {
            if(empty($val['regions'])){
                continue;
            }

            $area_ids = array_merge($area_ids,$val['regions']);

            //$rule_ids[] = array($val['id']);
        }

        $n_length = count($area_ids);
        $area_ids = array_unique($area_ids);
        $nn_length = count($area_ids);
        if($n_length != $nn_length)
        {
            $this->_error('存在重复地区');
            return false;
        }

        //查询所有的记录id内容
        $rule_ids = array();
        $cond = array();
        $cond['condition'] = "express_id='{$express_id}'";
        $temp_data = $this->find($cond);
        foreach($temp_data as $v)
        {
            $rule_ids[] = $v['id'];
        }

        //判断一个一个修改或者加入

        foreach($rules as $val)
        {
            if(in_array($val['id'],$rule_ids))
            {
                $f = $this->add($val);
            }
            else
            {
                unset($val['id']);
                $f = $this->edit($val,$val['id']);
            }

            if(!$f)
            {
                $this->_error('处理时发生错误');
                return false;
            }
        }



        return true;



    }

    /**
     * 取得所有的规则数据
     * @auth bzyy
     * 2015-7-24 18:10:59
     */
    public function rules($express_ids)
    {
        $cond = array();
        $cond['conditions'] = " express_id in (". implode(',',$express_ids) .") ";
        $cond['order'] = ' sort asc,id asc';
        $temp_data = $this->findAll($cond);

        $data = array();
        $ids = array();
        foreach($temp_data as $val)
        {
            $ids[] = $val['id'];
            $data[$val['express_id']][$val['id']] = $val;
        }

        //载入更多的地区信息
        $model = m('postruleregion');

        $condtion = array();
        $condtion['condtions'] = "rule_id in (". implode(',',$ids) .")";
        $temp_regions = $model->findAll($condtion);

        foreach($temp_regions as $val)
        {
            if(!isset($data[$val['express_id']][$val['rule_id']]))
            {
                continue;
            }

            $data[$val['express_id']][$val['rule_id']]['regions'][] = $val;
        }

        return $data;
    }

    /**
     * 更新对应的规则，
     * 规则可能对应的是多条数据
     * @auth bzyy
     * $addon 附加数据
     */
    public function editinfo($rules,$addon)
    {
        $type_default = 2;
        $type_free = 1;
        //验证规则的有效性
        $has_data = array();
        $model = m('postruleregion');

        foreach($rules as $val)
        {
            $save_data = array();

            $save_data['first_price'] = $val['first_price'];
            $save_data['first_value'] = $val['first_value'];
            $save_data['step']        = $val['step_value'];
            $save_data['step_price']  = $val['step_price'];
            $save_data['store_id']    = $addon['store_id'];
            $save_data['express_id']  = $addon['express_id'];
            $save_data['postal_id']   = $addon['postal_id'];

            //保存当前的数据
            if($val['type'] == 0)//默认类型
            {
                $save_data['ctype'] = 0;
                $save_data['sort'] = 2;
            }
            elseif($val['type'] == $type_free)//包邮
            {
                $save_data['ctype'] = $type_free;
                $save_data['sort'] = 1;
            }
            elseif($val['type'] == $type_default)//默认设置
            {
                $save_data['ctype'] = $type_default;
                $save_data['sort'] = 3;
            }
            //var_dump($save_data);exit;
            //保存处理
            $id = intval($val['id']);
            if($id && in_array($id,$addon['rules_ids']))
            {
                $flag = $this->edit($id,$save_data);
                if(!$flag)
                {
                    return false;
                }
            }
            else
            {
                $flag = $this->add($save_data);
                if(!$flag)
                {
                    return false;
                }
                $id = $flag;
            }

            $has_data[] = $id;
            //保存到
            $regions = $val['regions'];

            if(empty($regions) || !is_array($regions)){
                //看当前数据是什么类型，否则不能保存数据

                $regions = array();
            }


            $flag = $model->editregions($regions,$id,$addon);
            if(!$flag)
            {
                $this->_errors = $model->_errors;
                return false;
            }

        }
        $has_data = array_unique($has_data);
        $has_data = array_filter($has_data);
        $has_data[] = 0;

        //清除不存在的数据
        $sql_d = "select id from ".$this->table." where postal_id='{$addon['postal_id']}' and express_id='{$addon['express_id']}' and store_id='{$addon['store_id']}' and id not in(". implode(',',$has_data) .") ";
        $rols = $this->getAll($sql_d);

        if(!empty($rols))
        {
            $rols_ids = array();
            foreach($rols as $val)
            {
                $rols_ids[] = $val['id'];
            }

            $flag = $this->del($rols_ids);
            if(!$flag)
            {
                $this->_error('清理规则数据时发生错误');
                return false;
            }

        }




        return true;
    }


    /**
     * 删除规则
     * @auth bzyy
     * 2015-7-30 16:01:27
     */
    public function del($ids)
    {
        $ids[] = 0;
        //直接删除地区，在删除自己
        $sql = "delete from ".$this->_prefix."post_rule_region where rule_id in (". implode(',',$ids) .")";
        $f = $this->query($sql);
        if(!$f)
        {
            $this->_error('删除数据时失败');
            return false;
        }

        $sql = "delete from ".$this->table." where id in (". implode(',',$ids) .")";
        $f = $this->query($sql);
        if(!$f)
        {
            $this->_error('删除数据时失败');
            return false;
        }

        return true;

    }


    /**
     *
     */

} 